package org.itboys.weixin.interceptor;

import org.apache.commons.lang3.math.NumberUtils;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.admin.tools.WebConstants;
import org.itboys.commons.utils.cookie.CookieHolder;
import org.itboys.framework.spring.interceptor.ParamInitInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信自动绑定用户和微信ID的拦截器
 * @author ChenJunhui
 *
 */
public class WeixinAutoBindLoginInterceptor extends ParamInitInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		super.preHandle(request, response, handler);
		Long weixinUserId = AdminSessionHolder.getWeixinUserId();
		weixinUserId=(weixinUserId==null?CookieHolder.getWeixinUserId():weixinUserId);
		if(weixinUserId==null){
			String wui = request.getParameter(WebConstants.SessionKey.WEIXIN_USER_ID);
			if(wui!=null && NumberUtils.isDigits(wui)){
				weixinUserId = Long.parseLong(wui);
				request.getSession().setAttribute(WebConstants.SessionKey.WEIXIN_USER_ID, weixinUserId);
				CookieHolder.addWeixinUserIdToCookie(weixinUserId, 864000);
			}
		}
		
		Long weixinId = AdminSessionHolder.getWeixinId();
		weixinId=(weixinId==null?CookieHolder.getWeixinId():weixinId);
		if(weixinId==null){
			String _weixinId = request.getParameter(WebConstants.SessionKey.WEIXIN_ID);
			if(NumberUtils.isDigits(_weixinId)){
				weixinId = Long.parseLong(_weixinId);
				request.getSession().setAttribute(WebConstants.SessionKey.WEIXIN_ID, weixinId);
				CookieHolder.addWeixinIdToCookie(weixinId, 864000);
			}
		}
		return true;
	}
}
